<?php
/**
 * Created by PhpStrom
 * User: 郭碧云
 * Date: 2021/2/22 9:14
 * Desc:
 */

namespace App\Http\Controllers\Web;


use App\Facades\Site;
use App\Http\Controllers\BaseWebController;
use App\Lib\Logger;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Service\SiteService;
use App\Service\WxService;
use App\Service\MemberService;
include base_path()."/app/Lib/Phpqrcode.php";

class LoginController extends BaseWebController {
    protected $siteService;
    protected $wxService;
    protected $memberService;
    protected $appid;
    protected $secret;
    protected $site;
    public function _init() {
        $this->siteService = new SiteService("Admin.Site");
        $this->wxService = new WxService();
        $this->memberService = new MemberService("Admin.Member");
        $this->site = Site::config("wechat");
    }

    public function login(Request $request) {
        //验证
        if($this->request->isMethod("GET")){
            return view('web.user.login');
        }else{
            $params = $this->request->except('_token');
            if($params['type'] == 1){
                if(empty($params['username'])){
                    return $this->error(-1,"请填写用户名");
                }
                if(empty($params['password'])){
                    return $this->error(-1,"请填写密码");
                }
                $user['username'] = $params['username'];
                $user['password'] = $params['password'];
                //验证账号密码是否正确
                //验证登录信息
                if (!Auth::guard('web')->attempt($user)) {
                    $this->log(Logger::LOG_LEVEL_ERROR,'User','login',"web用户".$user["username"]."登录失败",[]);
                    return $this->error(-1,"账号/密码错误");
                }else{
                    return $this->success("","登录成功");
                }
                //记录日志
                $this->log(Logger::LOG_LEVEL_INFO,'User','login',"web用户".$params["username"]."登录成功",[]);
                return redirect(\route('index'));
            }else{
                dd($params);
            }
        }
    }
    public function qrcode(){
        if($this->request->isMethod("GET")){
            $token = substr(md5(time()), 0, 32);
            Cache::put($token,1,60);
            $callback = "http://dev.cepow.com/web/openid";
            $url = $this->wxService->setAppid($this->appid)->getCodeUrl($callback,$token);
            $path =  "/qrcode/{$token}.png";
            $outfile = base_path()."/public".$path;
            $level = 'L';
            $size = 5;
            $QRcode = new \QRcode();
            ob_start();
            $QRcode->png($url, $outfile, $level, $size, 4);
            ob_end_clean();

            return view("web.user.qrcode",compact(["token","path"]));
        }else{
            $data = $this->request->input();
            $value = Cache::get($data['token']);
            return $value;
        }
    }
    public function binding(){
        if($this->request->isMethod("GET")){
            $data = $this->request->input();
            return view("web.user.binding",compact(['data']));
        }else{
            $data = $this->request->except("_token");
            $user['username'] = $data['username'];
            $user['password'] = $data['password'];
            if (!Auth::guard('web')->attempt($user)) {
                return $this->error(-1,"账号/密码错误");
            }else{
                $bind['user_id'] = Auth::guard('web')->user()->id;
                $bind['bind_type'] = "wechat";
                $bind['bind_id'] = $data['openid'];
                $res = $this->memberService->createBind($bind);
                Cache::put($data['token'],2,60);
                if($res){
                    return $this->success("","登录成功");
                }else{
                    return $this->error(-1,"绑定失败");
                }
            }
        }

    }
    public function successBind(){
        return view("web.user.success");
    }
    public function setUserOpenid(){
        $data = $this->request->input();
        $result = json_decode($this->wxService->setAppid(($this->site)['appID'])->setSecret(($this->site)['appSecret'])->getOpenId($data['code']),true);
        $user = $this->memberService->setModel("UserBind")->first(['bind_id'=>$result['openid']]);
        if($user){
            Cache::put($data['state'],2,60);
            Auth::loginUsingId($user['user_id'],true);
            return redirect(route("web.success"));
        }else{
            Cache::put($data['state'],1,60);
            return redirect(route('web.binding',['openid'=>$result['openid'],'token'=>$data['state']]));
        }
    }
    //退出
    public function logout(){
        $msg = empty(getCurrentUser())?"未登录用户操作":"用户".getCurrentUser()["name"]."退出";
        $this->log(Logger::LOG_LEVEL_INFO,'User','logout',$msg,[]);
        auth('web')->logout();
        return redirect(\route("web.login"));
    }
}
